<?php

namespace app\client\services;

use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use app\admin\services\BaseService;
use think\facade\Validate;

class AlipayService extends BaseService
{
    protected static $dev=true;

    /**
     * 登录操作
     * @param $p
     * @return void
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function login($p){
        $rule=[
            'code'=>'require',
        ];
        $validate=Validate::rule($rule);
        if(!$validate->check($p)){
            api_return(500,$validate->getError());
        }
        Factory::setOptions(self::getOptions());
        $result=Factory::base()->oauth()->getToken($p['code']);
        if (empty($result->code)) {
            $openid=json_decode($result->httpBody)->alipay_system_oauth_token_response->open_id;
            api_return(200, '', CustomerService::login($openid, 'zfb', ($p['avatar']) ?? '', ($p['username']) ?? '用户未授权', ''));
        } else {
            api_return(500,$result->msg.','.$result->subMsg,$result);

        }
    }
    /**
     * 设置阿里云配置项目
     * @return Config
     */
    protected static function getOptions()
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';

        $options->appId='2021004101603853';

        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = file_get_contents(app()->getRootPath().'sensitive/AlipayClient/merchantPrivateKey.txt');
        //请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt
        $options->alipayCertPath = app()->getRootPath().'sensitive/AlipayClient/alipayCertPublicKey_RSA2.crt';
        //请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt
        $options->alipayRootCertPath = app()->getRootPath().'sensitive/AlipayClient/alipayRootCert.crt';
        //请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt
        $options->merchantCertPath =app()->getRootPath().'sensitive/AlipayClient/appCertPublicKey_2021004101603853.crt';
        //aesKey AES密钥
        $options->encryptKey='M9RvtxaXvpk3ONpZCnRFTg==';

        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        // $options->alipayPublicKey = '<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->';

        //可设置异步通知接收服务地址（可选）
        $options->notifyUrl = "<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->";

        return $options;
    }

    public static function decrypt($p) {

        $rule=[
            'cipherText'=>'require',
        ];
        $validate=Validate::rule($rule);
        if(!$validate->check($p)){
            api_return(500,$validate->getError());
        }
        Factory::setOptions(self::getOptions());
        $result=json_decode(Factory::util()->aes()->decrypt($p['cipherText']));
        if($result->code!=10000){
            api_return(500,'',$result->msg.','.$result->subMsg);
        }
        return $result;
    }

}
